package com.omg.weibo;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.omg.server.util.CommonUtil;
import com.omg.server.util.PropertiesHelper;
import com.omg.weibo.oauthv2.OAuthV2;
import com.omg.weibo.oauthv2.OAuthV2Client;
import com.omg.weibo.oauthv2.api.TAPI;
import com.omg.weibo.oauthv2.util.QHttpClient;

public class QQWeiBoSender {
	private static OAuthV2 oAuth = new OAuthV2();
	private static final Log log = LogFactory.getLog(QQWeiBoSender.class);
	private static boolean isInit = false;
	private static long lastSendTime = -1; //ms
	private static long timeOut = -1;
	
	public static void send(String title, String picUrl, String sourceUrl){
		String account = PropertiesHelper.getProperty("account");
		String password = PropertiesHelper.getProperty("password");
		if (!isInit){
			String clientSercret = PropertiesHelper.getProperty("qq_clientSERCRET");
			String clientId = PropertiesHelper.getProperty("qq_clientID");
			String redirectUri = PropertiesHelper.getProperty("qq_redirect_URI");
		    oAuth.setClientId(clientId);
	        oAuth.setClientSecret(clientSercret);
	        oAuth.setRedirectUri(redirectUri);
		}
		
		if (-1 == lastSendTime){
		    synchronized(QQWeiBoSender.class){
				if (-1 == lastSendTime){
					lastSendTime = System.currentTimeMillis();
				}
		    }
		}
		long currentTime = System.currentTimeMillis();
	    if (-1 == timeOut || (currentTime - lastSendTime) > timeOut){ //初始化或超时时重新登录
	    	synchronized(QQWeiBoSender.class){
			    if (-1 == timeOut || (currentTime - lastSendTime) > timeOut){
			        // 合成URL
		            String implicitGrantUrl = OAuthV2Client.generateImplicitGrantUrl(oAuth);
		            String responseData = GetQQAcessToken.getTokenInfo(implicitGrantUrl, account, password);
		            if (OAuthV2Client.parseAccessTokenAndOpenId(responseData, oAuth)) {
		        	    String expiresIn = oAuth.getExpiresIn();
		        	    if (CommonUtil.isNotEmpty(expiresIn)){
		        		   timeOut = Long.valueOf(expiresIn);
		        	    }
		        	    log.info("登录成功");
		            } else {
		        	    log.error("Fail to Get Access Token");
		                return;
		           }
			    }
	       }
	    }

	    /* -----------------------------------------授权流程 begin--------------------------------------------------*/
	    //自定制http连接管理器
	    QHttpClient qHttpClient = new QHttpClient(2, 2, 5000, 5000, null, null);
	    OAuthV2Client.setQHttpClient(qHttpClient);
	    qHttpClient.shutdownConnection();
	   
         /* -----------------------------------------简化测试参数 begin-----------------------------------------------
         * 下列每个参数的具体含义和取值，请参看其所在函数的doc文档
         */
        String format = "json";
        String clientip = "127.0.0.1";
        String jing = "";
        String wei = "";
        String syncflag = "";
        //String content = "3";// 注意：因为后台会对微博内容进行判重，所以在重复测试时加上变换部分++++++++

		/*
		*---------------------------------------- 微博相关测试例 begin---------------------------------------------
		*   注意：
		*   微博服务器对发微博的频率有限制，如果不加 sleep() 直接执行下列多条发微博操作， 
		*   可能会出现 ret=4 errcode=10 的错误码，意思是：发表太快，被频率限制 
		*/  
        TAPI tAPI = new TAPI(oAuth.getOauthVersion());//根据oAuth配置对应的连接管理器
        try { 
        	String content = title+ " 详情面面 " + sourceUrl;
            String response = tAPI.addPic(oAuth, format, content, clientip, jing, wei, picUrl, syncflag);
            log.info("发送返回信息:"+response);
        	//Thread.sleep (5000) ; 
        }
        catch (InterruptedException ie){
        	log.error(ie);
        }
        catch (Exception ie){
        	log.error(ie);
        }
        tAPI.shutdownConnection();//关闭连接管理器
	}
		
}
